package com.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crm.DTO.ActivityDto;
import com.crm.common.utils.StringUtils;
import com.crm.entity.Activity;
import com.crm.mapper.ActivityMapper;
import com.crm.service.ActivityService;
import com.crm.vo.ActivityVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, Activity> implements ActivityService {

    private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    private static final int LENGTH = 8;
    private static final SecureRandom random = new SecureRandom();

    @Autowired
    private ActivityMapper activityMapper;
    /**
     * 查询页面page
     * @param activityDto
     * @return
     */
    @Override
    public ActivityVo listPage(ActivityDto activityDto) {
        Page<Activity> page = new Page<>(activityDto.getPageNum(), activityDto.getPageSize());
        LambdaQueryWrapper<Activity> wrapper = new LambdaQueryWrapper<>();
        if(activityDto.getCode() != null){
            wrapper.eq(Activity::getCode, activityDto.getCode());
        }
        if(activityDto.getChannel()!= null){
            wrapper.eq(Activity::getChannel, activityDto.getChannel());
        }
        Map<String, Object> params = activityDto.getParams();

        // 1. 获取参数时，尝试将其转换为String，并去除首尾空格
        String beginCreateTimeStr = (params.get("beginCreateTime") != null) ? params.get("beginCreateTime").toString().trim() : null;
        String endCreateTimeStr = (params.get("endCreateTime") != null) ? params.get("endCreateTime").toString().trim() : null;
        String beginTimeStr = (params.get("beginTime") != null) ? params.get("beginTime").toString().trim() : null;
        String endTimeStr = (params.get("endTime") != null) ? params.get("endTime").toString().trim() : null;


        // 2. 使用 StringUtils.hasText() 进行判断 (Spring框架提供)
        // 或者使用 !isEmpty() 判断 (需要引入Apache Commons Lang或自己写)
        if(StringUtils.hasText(beginCreateTimeStr) && StringUtils.hasText(endCreateTimeStr)){
            wrapper.between(Activity::getCreateTime, beginCreateTimeStr, endCreateTimeStr);
        }
        if(StringUtils.hasText(beginTimeStr) && StringUtils.hasText(endTimeStr)){
            wrapper.between(Activity::getBeginTime, beginTimeStr, endTimeStr);
        }

        Page<Activity> activityPage = activityMapper.selectPage(page, wrapper);

        ActivityVo activityVo = new ActivityVo();
        activityVo.setActivities(activityPage.getRecords());//获取当前页数据列表
        activityVo.setPageSize(activityPage.getSize());//每页大小
        activityVo.setPageNum(activityPage.getCurrent());//当前页面
        activityVo.setTotalPage(activityPage.getPages());//总页数
        activityVo.setTotalCount(activityPage.getTotal());//总记录数
        return activityVo;
    }

    /**
     * 新增活动
     * @param activityDto
     */
    @Override
    public void saveActivity(ActivityDto activityDto) {
        Activity activity = new Activity();
        BeanUtils.copyProperties(activityDto,activity);



        activity.setCreateTime(new Date());

        // 手动转换 beginTime 和 endTime
        if (activityDto.getBeginTime() != null) {
            // 将 LocalDateTime 转换为 Date
            Date beginDate = Date.from(activityDto.getBeginTime().atZone(ZoneId.systemDefault()).toInstant());
            activity.setBeginTime(beginDate);
        }

        if (activityDto.getEndTime() != null) {
            // 将 LocalDateTime 转换为 Date
            Date endDate = Date.from(activityDto.getEndTime().atZone(ZoneId.systemDefault()).toInstant());
            activity.setEndTime(endDate);
        }
        //生成8位随机数
        StringBuilder sb = new StringBuilder(LENGTH);
        for (int i = 0; i < LENGTH; i++) {
            sb.append(CHARACTERS.charAt(random.nextInt(CHARACTERS.length())));
        }
        activity.setCode(sb.toString());

        super.save(activity);
    }




    /**
     * 删除活动
     * @param id
     */
    @Override
    public void deleteActivity(Long id) {
        activityMapper.deleteById(id);
    }

    /**
     * 回显活动数据
     * @param id
     * @return
     */
    @Override
    public Activity getActivityById(Long id) {
        LambdaQueryWrapper<Activity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Activity::getId, id);
        Activity activity = activityMapper.selectOne(wrapper);
        return activity;

    }

    /**
     * 修改活动
     * @param activityDto
     */
    @Override
    public void updateActivity(ActivityDto activityDto) {
        Activity activity = new Activity();

        LambdaQueryWrapper<Activity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Activity::getCode, activityDto.getCode());
        activity = activityMapper.selectOne(wrapper);

        BeanUtils.copyProperties(activityDto,activity);
        //查询活动数据
        activity.setUpdateTime(new Date());
        activityMapper.updateById(activity);
    }

    /**
     * 根据渠道查询活动数据
     * @param channel
     * @return
     */
    @Override
    public List<Activity> listActivityByChannel(Integer channel) {
        LambdaQueryWrapper<Activity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Activity::getChannel, channel);

        List<Activity> list = activityMapper.selectList(wrapper);
        log.info("根据渠道查询活动数据{}",list);
        return list;

    }

}
